<template>
	<view @click.stop="handleClick" class="i-buttons" :class="{dhover: dhover, hover: !disabled}"
		:style="{opacity: disabled ? 0.6 : 1, padding, borderRadius: radius, border,color,fontSize: size+'rpx', background: bgColor}"
		hover-class="hover" type="button">
		<slot></slot>
	</view>
</template>

<script lang="ts" setup>
	import {
		defineProps,
		defineEmits,
		ref
	} from 'vue'
	
	const props = defineProps({
		radius: {
			type: [Number, String],
			default: 32
		},
		border: {
			type: String,
			default: '1px solid #F3F4F5'
		},
		color: {
			type: String,
			default: '#A0A0AD'
		},
		size: {
			type: [Number, String],
			default: '28'
		},
		bgColor: {
			type: String,
			default: '#fff'
		},
		dhover: {
			type: [Boolean, String],
			default: false
		},
		padding: {
			type: String,
			default: '18rpx 32rpx'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		wait: {
			type: Number,
			default: 600
		}
	})
	const emit = defineEmits([
		'click'
	])
	
	// 使用 ref 保存 timer
	const timer = ref<number | null>(null)
	const lastClickTime = ref(0)
	
	const click = () => {
		if (props.disabled) {
			return
		}
		emit('click')
	}
	
	// 自定义防抖函数，更适合 uni-app 环境
	const handleClick = () => {
		if (props.disabled) {
			return
		}
		
		const now = Date.now()
		
		// 清除之前的定时器
		if (timer.value) {
			clearTimeout(timer.value)
			timer.value = null
		}
		
		// 首次点击或者距离上次点击超过等待时间，立即执行
		if (now - lastClickTime.value > props.wait) {
			lastClickTime.value = now
			click()
		} else {
			// 否则延迟执行
			timer.value = setTimeout(() => {
				lastClickTime.value = Date.now()
				click()
				timer.value = null
			}, props.wait)
		}
	}
</script>

<style lang="scss" scoped>
	.i-buttons {
		font-weight: 500;
		white-space: nowrap;
		@include flexRC;
	}

	// .i-buttons:active {
	// 	opacity: 0.8 !important;
	// }
	.hover:active {
		opacity: 0.6 !important;
	}

	.dhover:active {
		opacity: 0.6 !important;
		background-color: #D7D7E0;
	}
</style>
